package com.wechatapp.mengyao.poetry.core;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;

/**
 * @author yanghuaxu
 * @date 2025/5/21 8:47
 */
@Component
public class JwtUtils {
    // 密钥（至少32字节）
    private static String SECRET;
    // 过期时间（1天）
    private static final long EXPIRATION = 86400000L;

    public static final String AUTH_TOKEN_HEADER = "x-auth-token";

    public static final String AUTH_PLATFORM = "x-auth-platform";

    // 生成Token
    public static String generateToken(String openid, String unionid) {
        SecretKey key = Keys.hmacShaKeyFor(SECRET.getBytes());
        return Jwts.builder()
                .claim("openId", openid)
                .claim("unionId", unionid)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .signWith(key)
                .compact();
    }

    // 解析Token
    public static Claims parseToken(String token) {
        SecretKey key = Keys.hmacShaKeyFor(SECRET.getBytes());
        return Jwts.parserBuilder()
                .setSigningKey(key)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    @Value("${wechat.secret}")
    public void setSecret(String secret) {
        JwtUtils.SECRET = secret;
    }

}
